import Observer from './Observer';

/**
 * 完成某一目标的模块
 */
export default class Target {
  constructor(data) {
    this.data = data;

    //观察节点
    this.observer = new Observer('#list');

    this.init();
  }

  validateData(data) {
    const { username, password, age, gender } = data;

    //用户名或密码小于6位时 设置为空
    username.length < 6 && (data.username = '');
    password.length < 6 && (data.password = '');

    //年龄必须是数值 否则初始值为0
    typeof age === 'number' && (data.age = age);

    //性别不是数组设定的值时 初始化为男性
    !['male', 'female'].includes(gender) && (data.gender = 'male');
  }

  proxyData() {
    const _this = this;

    for (let key in this.data) {
      Object.defineProperty(_this, key, {
        get() {
          //更新日志
          this.observer.updateLog('get', key, _this.data[key]);

          //代理路径
          return _this.data[key];
        },
        set(newValue) {
          //更新日志
          this.observer.updateLog('set', key, _this.data[key], newValue);

          //代理修改的内容
          _this.data[key] = newValue;
        }
      });
    }
  }

  init() {
    //1.校验数据
    this.validateData(this.data);

    //2.代理数据
    this.proxyData();
  }
}
